'''
@create_time: 2025/10/23 下午4:05
@Author: GeChao
@File: path_manage.py
'''
from pathlib import Path
from typing import Union

ROOT_PATH = Path(__file__).resolve().parent.parent


class GetPath:
    '''
    路径管理模块
    1.查找项目中的目录
    2.查找项目中的文件
    '''

    def __init__(self, path=ROOT_PATH):
        self.path = Path(path)

    def get_dir_path(self, dir_name: str, is_str=False) -> Union[str, Path]:
        try:
            path_obj = [d for d in self.path.rglob(dir_name) if d.is_dir()]
            if len(path_obj) > 0:
                return str(path_obj[0]) if is_str else path_obj[0]
            else:
                raise FileNotFoundError(f'没有获取到名为{dir_name}的文件夹,请检查')
        except Exception as e:
            raise e

    def get_file_path(self, file_name: str, is_str=False) -> Union[str, Path]:
        try:
            path_obj = [d for d in self.path.rglob(file_name) if d.is_file()]
            if len(path_obj) > 0:
                return str(path_obj[0]) if is_str else path_obj[0]
            else:
                raise FileNotFoundError(f'没有获取到名为{file_name}的文件,请检查')
        except Exception as e:
            raise e

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        return


class ProjectFilePath:
    """
    单例模式
    查找项目中各个重要目录和文件
    """
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super(ProjectFilePath, cls).__new__(cls)
            with GetPath(ROOT_PATH) as p:
                # 测试用例路径
                cls.test_case_script_path = p.get_dir_path('case_scripts')
                cls._instance.test_case_report_path = p.get_dir_path('case_report')
                cls._instance.report_results_path = cls._instance.test_case_report_path / 'allure-results'
                cls._instance.test_result_db_path = p.get_file_path('auto_test_result_db.sqlite', is_str=True)
                cls._instance.test_web_ui_case_path = str(cls.test_case_script_path / 'web_ui')
                # cls._instance.run_env_conf = p.get_dir_path('env')
                cls._instance.env_init_conf = p.get_file_path('conf/clean_tasks.json')
                # cls._instance.generate_test_report_path = p.get_file_path('generate_test_report.py', is_str=True)
        return cls._instance


if __name__ == '__main__':
    p = ProjectFilePath()
    a=p.test_case_script_path
    b = p.env_init_conf
    print(b)






